home *** CD-ROM | disk | FTP | other *** search
- Path: ix.netcom.com!news
- From: jlilley@ix.netcom.com (John Lilley)
- Newsgroups: comp.lang.c++
- Subject: Re: Derivation and calling virtual functions
- Date: 29 Mar 1996 17:54:09 GMT
- Organization: Netcom
- Message-ID: <4jh841$1gp@dfw-ixnews6.ix.netcom.com>
- References: <graphix.828032689@spiff.cc.iastate.edu>
- NNTP-Posting-Host: den-co10-17.ix.netcom.com
- Mime-Version: 1.0
- Content-Type: Text/Plain; charset=US-ASCII
- X-NETCOM-Date: Fri Mar 29 11:54:09 AM CST 1996
- X-Newsreader: WinVN 0.99.7
-
- In article <graphix.828032689@spiff.cc.iastate.edu>, graphix@iastate.edu
- says...
- >
- > Say we have the following:
- >
- >class Base {
- >public:
- > virtual void func() { // some stuff }
- > virtual void write() { func(); };
- >};
- >
- >class Derived : public Base {
- >public:
- > void func() { // some stuff }
- > write(); { Base::func(); }
- >};
- >Derived inst;
-
-
- First of all, let's write this so that it works:
-
- class Base {
- public:
- virtual void func() { /*some stuff*/ }
- virtual void write() { func(); };
- };
-
- class Derived : public Base {
- public:
- void func() { /* some stuff */ }
- // need "void" before "write" to define the same method signature
- // According to the ARM 10.2 p.208 "It is an error for a derived
- // class function to differ from a base class' virtual function
- // in return type only.
- void write(); { Base::func(); }
- };
- Derived inst;
-
- However, the above changes do not in themselves answer the question,
- they only make it possible to explore what is really asked
- without confusion.
-
- Note that the "virtual" is implicit in the derived method
- delcarations and is unnecessary.
-
- > Now, when I call inst.write() it in turn calls Base::write() which in
- >turn calls Base::func(). Is there a way to instead have it call
- >Derived::func() if the instance is of type Derived? I hoped the
- >virtual keyword would help in this case.
-
- Whoa!!! Derived::write() *does not* call Base::write()!
-
- If we write it the way you wanted it to work:
-
- class Derived : public Base {
- public:
- void func() { printf("derived::func\n"); }
- void write() { Base::write(); }
- };
-
- main()
- {
- Derived inst;
- inst.write();
- }
-
- When run, this produces:
- derived::func
-
-
- Guess you forgot to compile with the -DWIM switch :-)
-
- john lilley
-
-
-